<?php
/**
 * IG_Sitemap
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Sitemap.php 524 2011-05-24 01:44:20Z mmxie $
 */
class IG_Sitemap
{
    private static $_cacheKey = 'lvan_sitemap';

    private static $_maps = array();

    public static function getMaps()
    {
        if (empty(self::$_maps)) {
            $cache = Zend_Registry::get('lvan_cache');
            if (!CACHE_ENABLE || null === (self::$_maps = $cache->load(self::$_cacheKey))) {
                $sitemap = new System_Model_Sitemap();
                $list = $sitemap->fetchAll();
                self::$_maps = self::buildMaps($list, 0);
                $cache->save(self::$_maps, self::$_cacheKey);
            }
        }
        return self::$_maps;
    }

    public static function navigation($module = null, $controller = null, $action = null, $params = array())
    {
        $arr = array($module, $controller, $action);
        $maps = self::getMaps();
        $navigation = array();
        foreach ($arr as $part) {
            if ($part !== null && is_string($part)) {
                if (isset($maps[$part])) {
                    $navigation[] = array('title' => $maps[$part]['title'], 'url' => '');
                    $maps = $maps[$part];
                }
            }
        }
        return self::toHtml($navigation);
    }

    private static function toHtml($navigation, $separator = ' >> ')
    {
        $html = '';
        foreach ($navigation as $nav) {
            $html .= $nav['title'] . $separator;
        }
        return rtrim($html, $separator);
    }

    private static function buildMaps($list, $parentId)
    {
        $maps = array();

        foreach ($list as $row) {
            if ($row->getParentId() == $parentId) {
                $maps[$row->getName()] = array('title' => $row->getTitle(), 'id' => $row->getSitemapId());
                $maps[$row->getName()] = array_merge($maps[$row->getName()], self::buildMaps($list, $row->getSitemapId()));
            }
        }
        return $maps;
    }
}